/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package transactions;

import item.Item;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import myJPA.Model;
import user.Customer;
import user.Employee;

/**
 *
 * @author Nacer Khalil
 */
public class ReservationMgt {
    
    public static int addReservation(Customer customer, Item item, Employee employee)
    {
        try
        {
            if(item.getAvailableCopies() == 0) //item can be reserved in this case
            {
                Reservation reservation = new Reservation(customer, item, employee);
                reservation.save();
                reservation.refresh();
                return reservation.getId();
            }
            else
                return 0;
            
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
            return 0;
        }
    }
    public static boolean placeItemOnHold(Item item)
    {
        try
        {
            EntityManager manager = Model.getEntityManager();
            Query query = manager.createNamedQuery("findReservationNotOnHold");
            query.setParameter("item", item);
            Reservation reservation = null;
            try
            {
                reservation = (Reservation) query.getSingleResult();
            }
            catch(Exception e)
            {
                reservation = null;
            }
            if(reservation != null)
            {
                reservation.setOnHold(true);
                reservation.update();
                return true;
            }
            else
            {
                item.setAvailableCopies(item.getAvailableCopies()+1);
                item.update();
                return false;
            }
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
            return false;
        }
    }
    
    public static boolean cancelReservation(Reservation reservation)
    {
        try
        {
            reservation.remove();
            return true;
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
            return false;
        }
    }
}
